#!/usr/bin/env python
import threading, re, socket, time, sys, random

interface = True

waitinglist = []
totallive = True
stayalive = True;

def tick(daft):
	pass


def start(daft):
	if "irc" in sys.argv:
		t = ircthread(daft)
		t.start()
	return True

def stop():
	global totallive
	global stayalive
	totallive = False
	stayalive = False;

def say(daft,r,sender,w):
	if "irc" in w.split(","):
		global waitinglist
		waitinglist += ['PRIVMSG '+sender+' : '+r+'\r\n']

class ircthread ( threading.Thread ):
	def __init__(self,daft):
		name = "daft"
		network = "irc.foonetic.net"
		channel = "#bots"
		threading.Thread.__init__(self)
		self.daft = daft
		self.name = name
		self.network = network
		self.channel = channel

	def run ( self ):
		global totallive
		global waitinglist
		global stayalive
		while totallive:
			port = 6667
			pingeth = time.time()
			talklevel = 2

			irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
			irc.connect ( ( self.network, port ) )

			print irc.recv ( 4096 )
			irc.send ( 'NICK '+self.name+'\r\n' )
			irc.send ( 'USER '+self.name+' '+self.name+' '+self.name+' :Acegiak\'s robotic lovechild\r\n' )
			irc.send ( 'MODE '+self.name+' +B\r\n')
			#irc.send ( 'AUTHSERV auth dobby 1JARE5Ww' ) # this auth section changes from server to server
			irc.send ( 'JOIN '+self.channel+'\r\n' )

			while stayalive == True:
				data = irc.recv ( 4096 )
				breakup = re.split('^:(.*?)!.*?PRIVMSG (.*?) :(.*?)$',data)
				for index, item in enumerate(breakup):
					print index, item

				if len(breakup) > 1:
					if breakup[2] != self.name:
						sender = breakup[2]
					elif breakup[1] != "":
						sender = breakup[1]
					if re.search('who.*?daft', breakup[3]):
						self.daft.say("I am daft",sender,"irc")
					if re.search('[Nn]ick[nN]ame', breakup[3]):
						self.daft.say("identify socks","Nickserv","irc")
						print "identifying"
					if re.match('^[\.]+\r\n?$', breakup[3]):
						self.daft.boom("AWKWARD",sender,"irc")
					if re.match('^[Bb]otsnack\r\n?$', breakup[3]):
						self.daft.boom("botsnack",sender,"irc")

					namesplit = [self.name[0:i] for i in range(3, len(self.name) + 1)]
					breakupsplit = re.split("(, |: )",breakup[3].lstrip(),1)
					ct = int(0.6+((time.time() - pingeth)/talklevel))
					if ct < 1:
						ct = 1
					words = breakupsplit[2 if len(breakupsplit) > 1 else 0]
					if breakupsplit[0] in namesplit or sender == "#"+self.name or sender[0] != "#":
						print "this is for me!"
						joiner = re.match('^!([a-z]+?) ([a-zA-Z0-9#\.]+)(.*?)$', words)
						if joiner:

							if joiner.group(1) == "join" and not re.match('#(xkcd)', joiner.group(3)):
								irc.send('JOIN '+joiner.group(2)+'\r\n')
							if joiner.group(1) == "become":
								irc.send('NICK '+joiner.group(2)+'\r\n')
								name = joiner.group(2)
							if joiner.group(1) == "shut" or joiner.group(1) == "shutup":
								pingeth = 0;
							if joiner.group(1) == "leave":
								irc.send('LEAVE '+joiner.group(2)+'\r\n')
							if joiner.group(1) == "tell":
								self.daft.say(joiner.group(2)+' :'+joiner.group(3).strip(),sender,"irc")
								pingeth = time.time();
							if joiner.group(1) == "talk" and joiner.group(1) == "more":
								talklevel = talklevel * 2
								if talklevel < 1:
									talklevel = 1
								self.daft.say('talk level set to '+str(talklevel),sender,"irc")
								
							if joiner.group(1) == "talk" and joiner.group(1) == "less":
								talklevel = talklevel / 2
								if talklevel < 1:
									talklevel = 1
								self.daft.say('talk level set to '+str(talklevel),sender,"irc")
						else:
					      		self.daft.boom(words.lower(),sender,"irc")

							pingeth = time.time();
					elif random.randrange(0,ct) < 2:
						self.daft.boom(words.lower(),sender,"irc")

				if re.match('^.*:Nickname is already in use.\r\n$',data):
				      self.name =random.choice(["bigger","better","sexier","badder","bolder","stronger","faster","harder"])+self.name
				      irc.send('NICK '+self.name+'\r\n')
				      irc.send('JOIN '+self.channel+'\r\n')

				if data.find("ou have not registered") != -1:
					stayalive = False
				if data.find("ERROR :Closing Link: ") != -1:
					stayalive = False
					time.sleep(6)
				if data == "0\r\n":
					stayalive = False
				if data.find ( 'PING' ) != -1:
					irc.send ( 'PONG ' + data.split() [ 1 ] + '\r\n' )
					print "pinged"
				if data.find ( 'KICK' ) != -1:
					irc.send ( 'JOIN '+self.channel+'\r\n' )
				if(len(waitinglist) > 0):
					for waitingmessage in waitinglist:
						irc.send(waitingmessage)
					waitinglist = []
			irc.close()

